// 获取应用实例
const app = getApp()
const api = app.globalData.api

Page({
    data: {
        info: [],
        khid: '',
        calendar: false,
        nowDate: new Date().getTime(),
        orderDate: '',
        detail: {},
        total: 0,
        count: 0,
        dateField: '',
        workshopPopup: false,
        linePopup: false,
        managerPopup: false,
        workshopOption: {},
        lineOption: {},
        managerOption: {},
        sourceOrderOption: {}
    },
    getLine: async function (field, workshop = '') {
        let res = await api.curlPost('?cla=inventoryOther&fun=line', {workshop: workshop})
        if (res.code === 1) {
            this.setData({
                [field]: res.data
            })
        }
    },
    // 关联生产计划单
    getOrderNo: async function () {
        let res = await api.curlGet('?cla=machiningInOrder&fun=getOrderNo')
        if (res.code === 1) {
            this.setData({
                sourceOrderOption: res.data
            })
        }
    },
    getManager: async function () {
        let res = await api.curlGet('?cla=inventoryOther&fun=staff')
        if (res.code === 1) {
            this.setData({
                managerOption: res.data
            })
        }
    },
    main: async function () {
        await this.getLine('workshopOption')
        await this.getManager()
        await this.getOrderNo()
    },
    // 更新本地数据
    syncStorage: async function (id) {
        let that = this,
            machiningInData = {}
        let res = await api.curlPost('?cla=machiningInOrder&fun=detail', {id: id})
        if (res.code === 1) {
            let result = res.data.result.detail
            for (const index in result) {
                machiningInData[index] = result[index]
            }
            wx.setStorageSync('machiningInfo', res.data.result.info)
            wx.setStorageSync('machiningInData', machiningInData)
            that.setData({
                total: api.total(machiningInData, ['price', 'num']),
                count: api.count(machiningInData),
                info: res.data.result.info,
                detail: machiningInData
            })
        }
    },
    onLoad: async function (options) {
        let that = this,
            id = options.id ? options.id : ''
        if (id) {
            await that.syncStorage(id)
        } else {
            wx.removeStorageSync('machiningInfo')
            wx.removeStorageSync('machiningInData')
        }
        await that.main()
    },
    // 刷新物料信息
    onShow: async function () {
        const that = this
        const machiningInData = wx.getStorageSync('machiningInData')
        that.setData({
            total: api.total(machiningInData, ['price', 'num']),
            count: api.count(machiningInData),
            detail: machiningInData
        })
    },
    onDisplay: function (e) {
        let obj = e.currentTarget.dataset
        this.setData({
            calendar: true,
            dateField: obj.field
        })
    },
    // 关闭
    onClose: function (e) {
        let obj = e.currentTarget.dataset
        if (obj) {
            this.setData({[obj.target]: false})
        }
    },
    goto(e) {
        return api.goto(e)
    },
    funRouting(type, detail) {
        const array = detail.value
        switch (type) {
            case 'recordDate':
            case 'demandDate':
                return api.formatDate(detail)
            // 选项与值相等
            case 'workshop':
                this.setData({
                    lineOption: this.getLine('lineOption', array['text'])
                })
                return array['text']
            // 选项与值为key value
            case 'lineName':
                this.setData({
                    ['info.lineId']: array['value']
                })
                return array['text']
            case 'staffName':
                this.setData({
                    ['info.manager']: array['value']
                })
                return array['text']
        }
    },
    // 确认选择
    onConfirm: function (e) {
        let obj = e.currentTarget.dataset
        let field = 'info.' + obj.field
        this.setData({
            [obj.target]: false,
            [field]: this.funRouting(obj.field, e.detail),
        })
    },
    getMaterial: async function(id){
        let that = this,
            machiningInData = {},
            object = {}
        let res = await api.curlPost('?cla=machiningInOrder&fun=getMaterial', {machiningOrderId: id})
        const original = wx.getStorageSync('machiningInData') ? wx.getStorageSync('machiningInData') : {}
        if (res.code === 1) {
            let result = res.data
            for (const index in result) {
                machiningInData[index] = result[index]
            }
            object = Object.assign(machiningInData, original)

            wx.setStorageSync('machiningInData', object)
            that.setData({
                total: api.total(object, ['price', 'num']),
                count: api.count(object),
                detail: object
            })
        }
    },
    onConfirmOrderNo: async function (e) {
        const obj = e.currentTarget.dataset
        const {value, text} = e.detail.value
        if(value.length > 0){
            await this.getMaterial(value)
        }
        this.setData({
            [obj.target]: false,
        })
    },
    showPopup: function (obj) {
        let popup = obj.currentTarget.dataset.show
        if (popup) {
            this.setData({
                [popup]: true
            });
        }
    },
    onDelete(obj) {
        const id = obj.currentTarget.dataset.id
        const {position, instance} = obj.detail;
        const machiningInData = wx.getStorageSync('machiningInData')
        switch (position) {
            // case 'left':
            // case 'cell':
            //     instance.close();
            //     break;
            case 'right':
                wx.showModal({
                    title: '提示',
                    content: '确定删除吗？',
                    success: (res) => {
                        if (res.confirm) {
                            delete machiningInData[id]
                            wx.setStorageSync('machiningInData', machiningInData)
                            instance.close()
                            this.setData({detail: machiningInData})
                            api.showToast('删除成功')
                        }
                    },
                })
                break;
        }
    },
    formSubmit: async function (e) {
        let obj = e.detail.value
        let machiningInData = wx.getStorageSync('machiningInData')
        let machiningInDataArray = Object.values(machiningInData)
        machiningInDataArray.forEach(function (item) {
            item['mxText'] = item['text']
            delete item['text']
        })
        obj['detail'] = api.arrayToJson(machiningInDataArray)
        if (obj) {
            let res = await api.curlPost('?cla=machiningInOrder&fun=edit', obj)
            if (res.code === 1) {
                wx.navigateTo({
                    url: 'detail?id=' + res.data
                })
                wx.removeStorageSync('machiningInData')
                api.showToast('新增成功', 'success')
            } else {
                api.showToast(res.warn)
            }
        }
    }
});